#include <iostream>
#include <opencv2/opencv.hpp>
#include "ov_detect.h"
#include "detector.h"
#include "common_structs.h"

using namespace std;
using namespace cv;

int main()
{
    Appconfig config;
    string json_path = "../../settings.json";
    load_config(config, json_path);
    OvO_Detector ov_detector;
    Appconfig* ptr = &config;
    ov_detector.Init(ptr);
    ov_detector.OvO_Init();

    VideoCapture cap("/home/cheakf/toe_aimbot_2023/video/6.avi");
    VideoWriter writer(
        "./output.avi", VideoWriter::fourcc('M','J','P','G'), cap.get(CAP_PROP_FPS), Size(640,640)
    );
    if (!cap.isOpened())
    {
        cout << "Error opening video file" << endl;
        return -1;
    }
    double fps = cap.get(CAP_PROP_FPS);
    int total_frames = cap.get(CAP_PROP_FRAME_COUNT);
    namedWindow("Video", WINDOW_NORMAL);
    Mat frame;
    int FPS = 0;
    auto infer_start = std::chrono::steady_clock::now();
    while (1)
    {
        //auto start = std::chrono::steady_clock::now();
        bool ret = cap.read(frame);
        if (!ret) break;
        ov_detector.push_img(frame);
        //auto end = std::chrono::steady_clock::now();
        //auto dur = std::chrono::duration<double, milli>(end-start).count();
        // cout << "dur" << dur << endl;
        ov_detector.detect();
        cv::resize(frame, frame, cv::Size(640,640));
        if (ov_detector.output_nms_.size() > 0)
        {
            s_armor armor = ov_detector.get_results(ov_detector.output_nms_);
            circle(frame, Point(armor.x_c, armor.y_c), 3, Scalar(0,255,0), -1);
            //cout << armor.x_c << armor.y_c << endl;
        }
        ov_detector.show_results(frame);
        // writer << frame;
        imshow("Video", frame);
        auto infer_end = std::chrono::steady_clock::now();
        auto duration = std::chrono::duration<double, milli>(infer_end-infer_start).count();
        if (duration > 1000) 
        {
            cout <<"FPS: " << FPS << endl;
            infer_start = infer_end;
            FPS = 0;
        }
        FPS++;
        waitKey(1000);
    }
    cout << "done" << endl;
    cap.release();
    destroyAllWindows();

    return 0;
}
